package com.nginx.web.util;

import java.io.*;

public class CmdUtil {

    public static String startNginx(String path){
        File dir = new File(path);
        return executeCmd(dir, "nginx.exe");
    }

    public static String reloadNginx(String path){
        File dir = new File(path);
        return executeCmd(dir, "nginx.exe -s reload");
    }

    public static String checkNginx(String path){
        File dir = new File(path);
        return executeCmd(dir, "nginx.exe -t");
    }

    public static String executeCmd(File dir , String cmd){
        try {
            // 调用CMD命令
            ProcessBuilder processBuilder = new ProcessBuilder("cmd.exe", "/c", cmd); // /c参数表示执行后关闭CMD窗口
            processBuilder.directory(dir);
            processBuilder.redirectErrorStream(true); // 将错误输出流与标准输出流合并
            Process process = processBuilder.start();

            // 获取命令输出结果
            InputStream inputStream = process.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "GBK")); // 设置编码为GBK
            String line;
            StringBuilder str = new StringBuilder();
            while ((line = reader.readLine()) != null) {
                str.append(line + "\n");
            }
            // 等待命令执行完成
            process.waitFor();
            return str.toString();
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void main(String[] args) {
        String pathname = "D:\\software\\nginx-1.22.0";
        String s = reloadNginx(pathname);
        System.out.println(s);
    }


}
